import axios from 'axios'
import type { AxiosRequestConfig } from 'axios'
import { showFailToast, showToast  } from 'vant'
import router from '@/router/index'
import { t } from '@/languages'
export enum TypeEnum {
  // json
  JSON = 'application/json',
  // form-data qs
  FORM_URL = 'application/x-www-form-urlencoded',
  // form-data  upload
  FORM_DATA = 'multipart/form-data',
}
const baseURL = import.meta.env.VITE_APP_BASEURL
const instance = axios.create({
  timeout: 30000,
  baseURL,
  headers: {
    'Cache-Control': 'no-cache'
  }
})
const whiteList = ['/api/app/resetpassword/', '/api/app/login/', '/api/app/register/', '/api/captcha/']

// 请求拦截配置
async function requestConfig(configs: any) {
  const token = localStorage.getItem('exToken')
  if(!whiteList.includes(configs.url) && !token) {
    
    router.push('/login')
    return  Promise.reject(new Error(t('Unauthorized operation')));
  }
  const headers = configs.headers || {}
  configs.headers = {
    ...headers,
    authorization: token
  }
  return configs
}

// 响应拦截配置
function responseConfig(response: any) {
  if(response.code !== 2000 && response.code !== 200) {
    if(response.code === 4001) {
      router.push('/login')
      localStorage.clear()
      return
    }
    showToast({
      message: response.data || response.msg,
      wordBreak: 'break-all',
      duration: 3000
    })
    
    return Promise.reject(response)
  }
  
  return response.data
}

// 配置请求拦截器
instance.interceptors.request.use(
  (config) => {
    return requestConfig(config)
  },
  (error: unknown): Promise<unknown> => {
    return Promise.reject(error)
  }
)

// 配置响应拦截器
instance.interceptors.response.use(
  (res) => {
    return responseConfig(res.config.originResult ? {...res, code: res.data.code} : (res.data || {}))
  },
  (error: unknown): Promise<unknown> => {
    return Promise.reject(error)
  }
)

type Payload<T = any> = T;

// 请求配置
interface RequestConfig extends AxiosRequestConfig {
  contentType?: string;
}

export function post<R = unknown>(
  url: string,
  requestData: Payload,
  config?: RequestConfig
) {
  return instance({
    url,
    method: 'POST',
    ...config,
    data: requestData
  }) as Promise<R>
}

export function get<R = unknown>(
  url: string,
  requestData: Payload,
  config?: RequestConfig
) {
  return instance({
    url,
    method: 'GET',
    ...config,
    params: requestData
  }) as Promise<R>
}

export function del<R = unknown>(
  url: string,
  requestData: Payload,
  config?: RequestConfig
) {
  return instance({
    url,
    method: 'DELETE',
    ...config,
    params: requestData
  }) as Promise<R>
}


export function put<R = unknown>(
  url: string,
  requestData: Payload,
  config?: RequestConfig
) {
  return instance({
    url,
    method: 'PUT',
    ...config,
    params: requestData
  }) as Promise<R>
}

export default instance
